package com.zsc.wxapp.services.impl;

import com.zsc.wxapp.context.BaseContext;
import com.zsc.wxapp.entity.PrintTask;
import com.zsc.wxapp.entity.vo.PriceTagVO;
import com.zsc.wxapp.entity.vo.PrintTaskVO;
import com.zsc.wxapp.exservices.Remote2;
import com.zsc.wxapp.mapper.PrintTaskMapper;
import com.zsc.wxapp.mapper.UserMapper;
import com.zsc.wxapp.services.PriceTagService;
import com.zsc.wxapp.services.PrintTaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class PrintTaskServiceImpl implements PrintTaskService {

    @Resource
    private PrintTaskMapper printTaskMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private Remote2 remote2;
    @Resource
    private PriceTagService priceTagService;

    /**
     * 获取打印任务列表
     * @return
     */
    @Override
    public List<PrintTaskVO> getPrintTaskList() {
        Long userId = BaseContext.getCurrentId();

        List<PrintTask> list = printTaskMapper.getPrintTaskList(userId);
        if (list.isEmpty()) {
            return null;
        }
        List<PrintTaskVO> result = new ArrayList<>();
        List<PriceTagVO> priceTagList;
        for (PrintTask task : list) {
            log.info("打印任务：{}", task);
            //获取提交打印信息的店铺名称
            String customUuid = userMapper.selectUserById(task.getSubmitUserId()).getCustomUuid();
            String custName = remote2.getCustomerInfoByCustUuid(customUuid).getCustName();
            String str = task.getPriceTagIds();
            // 去掉字符串中的方括号并按逗号分割，获取价签信息后收集为列表
            priceTagList = Arrays.stream(StringUtils.strip(str, "[]").split(","))
                    .map(Long::parseLong) // 将字符串转为 Long
                    .map(priceTagService::getPriceTagById) // 直接获取价签信息
                    .collect(Collectors.toList()); // 转换为 List

            result.add(PrintTaskVO.builder()
                    .id(task.getId())
                    .custName(custName)
                    .printNum(priceTagList.size())
                    .printList(priceTagList)
                    .build());
        }
        return result;
    }
}
